package com.chenjinyan.zuul.security;

import com.chenjinyan.zuul.dao.UserRepository;
import com.chenjinyan.zuul.entity.UserEntity;
import com.chenjinyan.zuul.utils.ResultUtil;
import com.chenjinyan.zuul.vo.Result;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import java.util.List;

/**
 * @author chenjinyan
 * @version 1.0
 */
public class CustomAuthenticationProvider implements AuthenticationProvider {


    private UserDetailsService userDetailsService;

    private BCryptPasswordEncoder bCryptPasswordEncoder;

    private UserRepository userRepository;


    public CustomAuthenticationProvider(UserDetailsService userDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder, UserRepository userRepository) {
        this.userDetailsService = userDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
        this.userRepository = userRepository;
    }


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Result result = ResultUtil.success();
        // 获取认证的用户名 & 密码
        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        List<UserEntity> list = userRepository.findByloginAccount(name);
        if (null == list || list.size() == 0 || list.size() > 1) {
            throw new BadCredentialsException("用户名错误");
        }
        UserEntity userEntity = list.get(0);
        // 认证逻辑
        if (name.equals(userEntity.getLoginAccount()) && bCryptPasswordEncoder.matches(password, userEntity.getPassword())) {
            // 生成令牌
            Authentication auth = new UsernamePasswordAuthenticationToken(name, password);
            return auth;
        } else {
            throw new BadCredentialsException("密码错误");
        }
    }

    // 是否可以提供输入类型的认证服务
    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
